package com.eco.fanliapp.shengyaappeurekeclient.utils;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
public class LuceneUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    private static final Logger log = LoggerFactory.getLogger(LuceneUtil.class);
    //Lucene索引文件路径
//    private static String dir = "/home/nginx/fanli/lucene/index/";
    private static Directory directory;

    private static IndexReader indexReader;
    private static IndexWriter indexWriter;

    private static IndexSearcher indexSearcher;

    public static String TEXT_FIELD = "text";

    public synchronized Directory getDirectory(String dir) throws IOException {
        if (directory == null) {
            try {
                //索引存放的位置，设置在当前目录中
                directory = FSDirectory.open(Paths.get(dir));
            } catch (Exception e) {

            }
        }
        return directory;
    }

    public synchronized IndexReader getIndexReader(String dir) throws IOException {
//        if (indexReader == null) {
        try {
            //创建索引的读取器
            indexReader = DirectoryReader.open(getDirectory(dir));
        } catch (Exception e) {

        }
//        }
        return indexReader;
    }

    public synchronized IndexWriter getIndexWriter(String dir) throws IOException {
//        if (indexWriter == null) {
        try {
            //创建索引的读取器
            indexWriter = new IndexWriter(getDirectory(dir), new IndexWriterConfig(new IKAnalyzer()));
        } catch (Exception e) {

        }
//        }
        return indexWriter;
    }

    public synchronized IndexSearcher getIndexSearcher(String dir) throws IOException {
//        if (indexSearcher == null) {
        try {
            //创建一个索引的查找器，来检索索引库
            indexSearcher = new IndexSearcher(getIndexReader(dir));
        } catch (Exception e) {

        }
//        }
        return indexSearcher;
    }


    public void tearDown() throws Exception {
        if (indexReader != null) {
            indexReader.close();
        }
    }

    public Sort getSortByField(String field, Boolean desc) {
        Sort sort = new Sort();
        sort.setSort(new SortField(field, SortField.Type.DOC, desc));
        return sort;
    }

    public Sort getSortByFloatField(String field, Boolean desc) {
        Sort sort = new Sort();
        sort.setSort(new SortField(field, SortField.Type.FLOAT, desc));
        return sort;
    }

    /*
     * 刪除索引
     *
     */
    public long deleteIndex(String itemid, String dir) {
        try {
//            Analyzer analyzer = new IKAnalyzer();//中文分词
//
//            //创建索引写入配置
//            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
//
//            //创建索引写入对象
//            IndexWriter indexWriter = new IndexWriter(getDirectory(), indexWriterConfig);
            IndexWriter indexWriter = getIndexWriter(dir);
            // 删除title中含有关键词“Spark”的文档
            long count = indexWriter.deleteDocuments(new Term("itemid", itemid));
            indexWriter.commit();
//            indexWriter.close();
            log.info("删除完成:" + count);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0L;
    }

    //添加索引
    public long write(Document doc, String dir) {
        long start = System.currentTimeMillis();
        try {

//            Version version = Version.LUCENE_7_1_0;
//
//            Analyzer analyzer = new IKAnalyzer();//中文分词
//
//            //创建索引写入配置
//            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
//
//            //创建索引写入对象
//            IndexWriter indexWriter = new IndexWriter(getDirectory(), indexWriterConfig);
            IndexWriter indexWriter = getIndexWriter(dir);
            //将doc对象保存到索引库中
            Long count = indexWriter.addDocument(doc);

            indexWriter.commit();
            //关闭流
//            indexWriter.close();
            long end = System.currentTimeMillis();
            log.info("索引花费了" + (end - start) + " 毫秒");
            return count;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    public long query(String keyword) {
        try {
            Analyzer analyzer = new IKAnalyzer();//中文分词
            //查询解析器
            QueryParser queryParser = new QueryParser("itemid", analyzer);

            //使用分词器对用户的输入内容进行分词，得到要进行查询的关键词集
            Query query = queryParser.parse(keyword);

            //使用检索器对query进行检索，得到结果集
            TopDocs hits = indexSearcher.search(query, 2);

            //显示结果数量
            Long i = hits.totalHits;

            return i;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0L;
    }

    public long updateIndex(String itemid, Document doc, String dir) throws IOException {

        try {
            Analyzer analyzer = new IKAnalyzer();//中文分词

            //创建索引写入配置
            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);

            //创建索引写入对象
            IndexWriter indexWriter = new IndexWriter(getDirectory(dir), indexWriterConfig);

            long count = indexWriter.updateDocument(new Term("itemid", itemid), doc);
            log.info("更新文档:" + count);
            indexWriter.close();
            return count;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0L;
    }

}
